{{#contentFor "Styles"}}
<style type="text/css">
    #tbodyTables .alert,
    #divTable.alert {
        margin-bottom: 5px;
        padding: 5px 10px;
        cursor: pointer;
    }

    #divTable.alert {
        cursor: initial;
        user-select: none;
        line-height: 24px;
        padding: 1px 1px 1px 10px;
    }

    #tbodyTables .alert h5 {
        font-size: 14px;
        font-weight: bold;
        position: relative;
        margin-top: 5px;
        margin-bottom: 5px;
    }

    #tbodyTables .alert h5 .badge {
        position: absolute;
        font-weight: bold;
        display: inline-block;
        font-size: 1em;
        padding: 0;
        top: -10px;
        right: -10px;
        border-radius: 50%;
        background: rgb(135, 208, 104);
        border: 1px solid rgb(135, 208, 104);
        width: 36px;
        height: 36px;
        line-height: 34px;
        text-align: center;
        vertical-align: middle;
    }

    #tbodyTables .alert .extra span:not(:first-child),
    #divTable.alert .extra span:not(:first-child) {
        margin-left: 10px;
    }

    .fixed-table-container tbody td .th-inner,
    .fixed-table-container thead th .th-inner {
        line-height: 18px;
    }

    #divContainer{
        overflow-y: auto;
    }
</style>
{{/contentFor}}
{{#contentFor "Scripts"}}
<script type="text/javascript" src="/scripts/juicer-min.js"></script>
<script type="text/javascript" src="/scripts/handlebars.js"></script>
<script type="text/javascript" src="/scripts/data-render.js"></script>
<script type="text/javascript">
    var tables = [];
    var toggleIndex = 0;
    var currentColumns = [];
    var dbIndex = {{ dbIndex }}, schema = '{{schema}}', dbType = '{{dbType}}', tableName;

    $(function () {
        $(window).resize(function(){
            let maxHeight = ($(window).innerHeight() - 247) + 'px';
            let maxHeight2 = ($(window).innerHeight() - 165) + 'px';

            $('#tbodyTables').css('max-height', maxHeight);
            $('#divContainer').css('max-height', maxHeight2);
        });

        $(window).resize();

        $('#ddlDbServers').change(function () {
            var selected = $(this).find('option:selected');
            dbIndex = selected.val();
            dbType = selected.attr('data-type');

            $.ajax({
                method: 'get',
                url: `/api/${dbType}/${dbIndex}/dbs`,
                dataType: 'json'
            }).then(function (rs) {
                if (!rs.success) {

                } else {
                    $('#ddlDb').html('');
                    rs.datas.forEach(function (item) {
                        $('#ddlDb').append(`<option value="${item.SCHEMA_NAME}"${item.SCHEMA_NAME.toLowerCase() == '{{schema}}'.toLowerCase() ? " selected" : ""} data-type="${dbType}">${item.SCHEMA_NAME}</option>`);
                    });

                    $('#ddlDb').trigger('change');
                }
            });
        });

        $('#ddlDb').change(function () {
            dbIndex = $('#ddlDbServers > option:selected').val();
            schema = $(this).find('option:selected').val();
            dbType = $(this).find('option:selected').attr('data-type');

            GetTables(dbIndex, schema, dbType);
        });

        $('#ddlDbServers').trigger('change');

        $('#btnSearch').click(function () {
            $(this).prop('disabled', true);

            var searchKey = $('#txtSearch').val().toLowerCase();
            var filters = tables.filter(function (item) {
                if (!searchKey) {
                    return true;
                }

                return item.table_name.toLowerCase().indexOf(searchKey) != -1 || (item.table_comment || '').toLowerCase().indexOf(searchKey) != -1;
            });

            var dbIndex = $('#ddlDbServers > option:selected').val();
            var schema = $('#ddlDb > option:selected').val();

            InitTables(dbIndex, schema, filters);
        });

        $('#btnReset').click(function () {
            $('#txtSearch').val('');

            $('#btnSearch').trigger('click');
        });

        $('#txtSearch').keydown(function () {
            if (event.keyCode == 13) {
                $('#btnSearch').trigger('click');
            }
        });

        $('#tgTableInfo > label.btn').on('click', function () {
            var type = $(this).parent().find('#' + $(this).prop('for')).val();

            switch (type) {
                case '字段':
                    toggleIndex = 0;
                    GetColumns(dbIndex, schema, tableName);
                    break;
                case '数据':
                    toggleIndex = 1;

                    $.ajax({
                        method: 'post',
                        url: `/api/${dbType}/${dbIndex}/${schema}/${tableName}/datas`,
                        success: function (rs) {
                            let data = rs.datas[0];

                            let props = Object.getOwnPropertyNames(data || {});

                            window.dataRender({
                                el: '#divContainer',
                                datas: rs.datas,
                                columns: props.map(p => {
                                    return {
                                        title: p,
                                        field: p,
                                        width: p.length * 25
                                    };
                                })
                            });
                        }

                    });

                    break;
                case '脚本':
                    toggleIndex = 2;
                    $.ajax({
                        method: 'get',
                        url: `/api/${dbType}/${dbIndex}/${schema}/${tableName}/ddl`,
                        dataType: 'json'
                    }).then(function (rs) {
                        $('#divContainer').html(`<div class="panel panel-primary"><div class="panel-body"><pre style="max-height:520px;overflow-y:auto;">${rs.data['Create Table']}</pre></div></div>`);
                    });

                    break;
            }
        });
    });

    function GetTables(dbIndex, schema, dbType) {
        $('#tbodyTables').html('<tr><td colspan="9" class="text-warning">正在查询中，请稍后...</td></tr>');
        $.ajax({
            method: 'GET',
            url: `/api/${dbType}/${dbIndex}/${schema}/tables`,
            dataType: 'json'
        }).then(function (rs) {
            tables = [];

            if (!rs.success) {
                $('#tbodyTables').html(`<tr><td colspan="9" class="text-danger">${rs.msg}</td></tr>`);
            } else {
                tables = rs.datas;

                InitTables(dbIndex, schema, rs.datas);
            }
        });
    }

    function InitTables(dbIndex, schema, tables) {
        $('#tableCount').text(tables.length);
        $('#btnSearch').prop('disabled', false);
        $('#tbodyTables').html(juicer($('#tplTables').html(), { dbIndex: dbIndex, schema: schema, list: tables }));

        $('#tbodyTables .alert').hover(function () {
            $(this).removeClass('alert-info').addClass('alert-success');
        }, function () {
            $(this).removeClass('alert-success').addClass('alert-info');
        }).click(function () {
            var table = tables[$(this).attr('data-db-table-index')];
            tableName = table.table_name;

            $(this).addClass('alert-warning');
            $('#tbodyTables .alert').not(this).removeClass('alert-warning');

            var current = $(`#tgTableInfo > label.btn:eq(${toggleIndex})`);

            current.trigger('click');
        });

        $('#tbodyTables .alert:eq(0)').trigger('click');
    }

    function GetColumns(dbIndex, schema, tableName) {
        $.ajax({
            method: 'post',
            url: `/db/table/${dbIndex}/${dbType}/${schema}/${tableName}`,
            dataType: 'html'
        }).then(function (rs) {
            $('#divContainer').html(rs);

            // layui.table.init('dgColumns', { height: 490, limit: 500 });
            currentColumns = JSON.parse($('#divContainer').find('p.sr-only').text()).datas;
        });
    }
    </script>
    <script id="tplTables" type="text/template">
        {@if list.length==0 }
            <div class="text-warning">
                未找到符合条件的表！
            </div>
        {@else}
            {@each list as item, index}
            <div class="alert alert-info" data-db-index="${dbIndex}" data-db-schema="${schema}" data-db-table-index="${index}" data-db-table="${item.table_name}">
                <h5>
                    <span class="badge">${ parseInt(index)+1 }</span>
                    ${item.table_name}(${item.table_rows})
                </h5>
                <div class="extra">
                    {@if item.table_comment}<i>${item.table_comment}</i>{@/if}
                </div>
            </div>
            {@/each}
        {@/if}
    </script>
{{/contentFor}}

<div class="card">
    <div class="card-body">
        <div class="row align-items-center">
            <div class="col-3">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text">数据库服务器</span>
                    </div>
                    <select id="ddlDbServers" class="form-select">
                        {{#each dbs}}
                        <option value="{{@index}}" data-type="{{type}}" {{selected @index }}>{{name}}</option>
                        {{/each}}
                    </select>
                </div>
            </div>
            <div class="col-4">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text">数据库</span>
                    </div>
                    <select id="ddlDb" class="form-select"></select>
                </div>
            </div>
            <div class="col">
                <div id="tgTableInfo" class="btn-group float-end" role="group">
                    <input id="rbType1" name="rbType" class="btn-check" type="radio" autocomplete="off" value="字段" />
                    <label for="rbType1" class="btn btn-outline-primary">
                        <i class="bi bi-info-circle-fill"></i> 字段
                    </label>

                    <input id="rbType2" name="rbType" class="btn-check" type="radio" value="数据" autocomplete="off" />
                    <label for="rbType2" class="btn btn-outline-primary">
                        <i class="bi bi-card-list"></i> 数据
                    </label>

                    <input id="rbType3" name="rbType" class="btn-check" type="radio" value="脚本" autocomplete="off" />
                    <label for="rbType3" class="btn btn-outline-primary">
                        <i class="bi bi-file-code"></i> 脚本
                    </label>

                    <input id="rbType4" name="rbType" class="btn-check" type="radio" value="实体" autocomplete="off" />
                    <label for="rbType4" class="btn btn-outline-primary">
                        <i class="bi bi-pencil-fill"></i> 实体
                    </label>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-4">
        <div class="card card-primary">
            <div class="card-header">数据库表详情(当前库：{{dbName}} 共计<span id="tableCount"></span>张表)</div>
            <div class="card-body">
                <div class="input-group" style="margin-bottom:5px;">
                    <input id="txtSearch" type="text" class="form-control" placeholder="表名称/说明" />
                    <span class="btn-group">
                        <button id="btnSearch" type="button" class="btn btn-primary" disabled>
                            <i class="bi bi-search"></i> 搜索
                        </button>
                        <button id="btnReset" type="button" class="btn btn-danger">
                            <i class="bi bi-trash"></i> 清除
                        </button>
                    </span>
                </div>
                <div id="tbodyTables" style="max-height:420px;overflow-y:auto;"></div>
            </div>
        </div>
    </div>
    <div id="divTableDetail" class="col-8">
        <div id="divContainer"></div>
    </div>
</div>